package com.redfox.newapp.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.redfox.newapp.R;
import com.redfox.newapp.adapter.AndDevAdapter;
import com.redfox.newapp.utils.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by redfox on 2017/3/17.
 */

public class BaseArticleFragment extends Fragment implements Runnable, Handler.Callback{
    private final String TAG = "AndDevFragment";
    private final int WM_GET_RESULT = 0x1001;

    private Context mContext;
    private XRecyclerView mRecycleView;
    private AndDevAdapter mAdapter;
    private Handler mHandler;
    private String mParam;
    private int mPage = 1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Bundle bundle = this.getArguments();
        if (bundle != null)
            mParam = bundle.getString("param");

        mContext = container.getContext();
        View v = inflater.inflate(R.layout.anddev_frag_layout, container, false);
        mRecycleView = (XRecyclerView) v.findViewById(R.id.anddev_view);
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapter = new AndDevAdapter(container.getContext());
        mRecycleView.setAdapter(mAdapter);
        mRecycleView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mRecycleView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                openNextPage();
            }
        });

        mHandler = new Handler(this);
        Thread thread = new Thread(this);
        thread.start();
        return v;
    }

    public static AndDevFragment newInstance(String param) {
        AndDevFragment fragment = new AndDevFragment();
        Bundle bundle = new Bundle();
        bundle.putString("param", param);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void run() {
        ArrayList<AndDevAdapter.ItemData> results = new ArrayList<>();
        try {
            HttpRequest req = HttpRequest.get("http://gank.io/api/data/" +mParam+"/20/" + mPage);
            if (req.ok()) {
                JSONObject json = new JSONObject(req.body());
                if (json.getBoolean("error") == false) {
                    JSONArray array = json.getJSONArray("results");
                    for (int i = 0; i < array.length(); ++i) {
                        JSONObject r = array.getJSONObject(i);
                        AndDevAdapter.ItemData item = new AndDevAdapter.ItemData();
                        if (r.has("images")) {
                            item.imageUrl = r.getJSONArray("images").getString(0);
                        }

                        item.url = r.getString("url");
                        item.title = r.getString("desc");
                        item.who = r.getString("who");
                        item.publish_date = r.getString("publishedAt");
                        results.add(item);
                    }
                }
            }
        }
        catch (Exception e) {
            Log.d(TAG, "run: " + e.getMessage());
        }

        Message msg = mHandler.obtainMessage(WM_GET_RESULT, results);
        mHandler.sendMessage(msg);
    }

    @Override
    public boolean handleMessage(Message msg) {

        if (msg.what == WM_GET_RESULT) {
            ArrayList<AndDevAdapter.ItemData> items = (ArrayList<AndDevAdapter.ItemData>) msg.obj;
            for (AndDevAdapter.ItemData item : items)
                mAdapter.addItem(item);

            mAdapter.notifyDataSetChanged();
            mRecycleView.loadMoreComplete();
            return true;
        }

        return false;
    }

    public void openNextPage() {
        mPage++;
        Thread thread = new Thread(this);
        thread.start();
    }
}
